package com.liu.system.manage.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.common.utils.IdWorker;
import com.liu.common.utils.JacksonUtil;
import com.liu.system.manage.domain.DMenu;

import com.liu.system.manage.domain.Option;
import com.liu.system.manage.domain.TreeNode;
import com.liu.system.manage.mapper.MenuMapper;
import com.liu.system.manage.service.IMenuService;
import com.liu.system.manage.util.MenuTreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class MenuServiceImpl extends ServiceImpl<MenuMapper,DMenu>implements IMenuService {

    @Autowired
    MenuMapper menuMapper;


    @Autowired
    IdWorker idWorker;





    @Override
    public Page<DMenu> queryUserForPage(int page, int limit, String query) {
        return null;
    }

    @Override
    public boolean updateMenu(DMenu menu) {
        return this.saveOrUpdate(menu);
    }

    @Override
    public boolean addMenu(DMenu menu) {
        menu.setId(idWorker.nextId()+"");
        menu.setCreateTime(new Date());

        return this.save(menu);
    }

    @Override
    public boolean delete(String id) {



        return  this.removeById(id);
    }



    @Override
    public List<Option> getOptions() {
        List<Option> options =new ArrayList<>();

        this.list().forEach(e->{
            if(e.getType()<2){
                Option option = new Option();
                option.setValue(e.getId());
                option.setLabel(e.getName());
                options.add(option);
            }

        });
        Option base= new Option("0","根");
        options.add(base);

        return options;
    }




    @Override
    public List<TreeNode> getMenuTree(String query,String id) {
        QueryWrapper wrapper = new QueryWrapper();


        if(!StringUtils.isEmpty(query)){
            wrapper.like("name",query);
        }
        wrapper.orderByAsc("sort");

         List<DMenu> menus=  this.list(wrapper);
        log.info(JacksonUtil.printJson(menus));
        return MenuTreeUtil.bulid(menus);
    }
}
